package microservice.demo.servicecomb.course.helloservice.endpoint;

import java.time.Clock;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.apache.commons.lang3.StringUtils;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.apache.servicecomb.serviceregistry.RegistryUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;

@RestSchema(schemaId = "hello")  // 该注解声明这是一个REST接口类，Java-Chassis会扫描这个类，根据它的代码生成微服务契约
@RequestMapping(path = "/hello-service/v0") // @RequestMapping 是Spring的注解，这里在使用Spring MVC风格开发REST接口
public class HelloEndpoint {
  private static final Logger LOGGER = LoggerFactory.getLogger(HelloEndpoint.class);

  private static final String SAY_HELLO_PREFIX = "hello.sayHelloPrefix";

  private Clock clock = Clock.systemDefaultZone();

  private DynamicStringProperty sayHelloPrefix = DynamicPropertyFactory.getInstance()
      .getStringProperty(SAY_HELLO_PREFIX, "", notifyConfigRefreshed());

  private Runnable notifyConfigRefreshed() {
    return () -> LOGGER.info("config[" + SAY_HELLO_PREFIX + "] changed to [{}]!", sayHelloPrefix.getValue());
  }

  @GetMapping(path = "/hello")
  public String sayHello(@RequestParam(value = "name") String name) {
    if ("0.0.1".equals(RegistryUtils.getMicroservice().getVersion())) {
      return sayHelloPrefix.getValue() + name;
    }

    return sayHelloPrefix.getValue() + name + ". " + generateGreeting();
  }

  private String generateGreeting() {
    Calendar calendar = new GregorianCalendar();
    int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
    if (hourOfDay < 12) {
      return "Good morning.";
    }
    if (hourOfDay < 18) {
      return "Good afternoon.";
    }
    if (hourOfDay < 22) {
      return "Good evening.";
    }
    return "Good night.";
  }

  @PostMapping(path = "/greeting")
  public GreetingResponse greeting(@RequestBody Person person) {
    if (StringUtils.isEmpty(person.getName()) || null == person.getGender()) {
      throw new DemoException("A certain property is absent");
    }

    GreetingResponse greetingResponse = new GreetingResponse();
    if (Gender.MALE.equals(person.getGender())) {
      greetingResponse.setMsg("Hello, Mr." + person.getName());
    } else {
      greetingResponse.setMsg("Hello, Ms." + person.getName());
    }
    greetingResponse.setTimestamp(clock.millis());

    return greetingResponse;
  }
}
